<template>
  <div class="app-container">
    <el-row>
      <el-col :span="12">
        <p class="addTitle">编辑考勤班次信息</p>
      </el-col>
      <el-col :span="12" style="display: flex; justify-content: end; align-items: center">
        <el-button type="primary" @click="saveForm" > 保存 </el-button>
        <el-button @click="goBack"> 返回 </el-button>
      </el-col>
    </el-row>
    <el-form :model="tableData">
      <el-form-item label="班次名称">
        <el-input v-model="tableData[0].name" placeholder="请输入班次名称" />
      </el-form-item>
      <el-form-item label="班次类型">
        <el-radio-group v-model="tableData[0].type">
          <el-radio :value="1">固定班次</el-radio>
          <el-radio :value="2">弹性班次</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="打卡方式">
        <el-radio-group v-model="tableData[0].way">
          <el-radio :value="1">GPS</el-radio>
          <el-radio :value="2">WiFi</el-radio>
          <el-radio :value="3">两种方式均可</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="班次设置">
        <span>工作时间总计 {{ diffInMs }}</span>
        <el-table :data="tableData" v-if="isEditOne">
          <el-table-column label="开始时间" >
            <template #default="{ row }">
              <el-time-picker v-model="row.startTime" placeholder="请选择" value-format="HH:mm:ss" is-range />
            </template>
          </el-table-column>
          <el-table-column label="结束时间" >
            <template #default="{ row }">
              <el-time-picker v-model="row.endTime" placeholder="请选择" value-format="HH:mm:ss" is-range />
            </template>
          </el-table-column>
          <el-table-column label="生效时间">
            <template #default="{ row }">
              <el-date-picker v-model="row.effectiveTime" type="datetime" placeholder="请选择" value-format="YYYY-MM-DD HH:mm:ss" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default>
              <el-button link type="primary" @click="saveTable(1)">保存</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-table :data="tableData" v-else>
          <el-table-column v-for="(obj, index) in tableOneHeader" :key="index" :label="obj.label">
            <template #default="{ row }">
              <span v-if="obj.prop === 'startTime'">
                {{ row.startTime }}
              </span>
              <span v-else-if="obj.prop === 'endTime'">
                {{ row.endTime }}
              </span>
              <span v-else>
                {{ row[obj.prop] }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button link type="primary" @click="editTable(1, row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="打卡方式">
        <span>根据办公地点考勤</span>
        <el-table :data="tableData[0].attendanceAddressType">
          <el-table-column label="考勤地址">
            <template #default="{ row }">
              <el-input v-if="row.isEdit" :disabled="true" v-model="row.attendanceAddress" />
              <span v-else> {{ row.attendanceAddress }}</span>
            </template>
          </el-table-column>
          <el-table-column label="有效范围(米)">
            <template #default="{ row }">
              <el-input-number v-if="row.isEdit" v-model="row.effectiveRange" :min="1" :max="1000" controls-position="right" style="width: 100%" />
              <span v-else>{{ row.effectiveRange }}</span>
            </template>
          </el-table-column>
          <el-table-column label="适用人员">
            <template #default="{ row }">
              <el-select
                v-model="row.attendanceUsersId"
                multiple
                collapse-tags
                collapse-tags-tooltip
                placeholder="请选择"
                @blur="showNickname(row.attendanceUsersId, row)"
                v-if="row.isEdit"
              >
                <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName" :value="item.userId" />
              </el-select>
              <div v-else>
                <span v-for="item in row.attendanceUsersName">{{ item }}&nbsp; </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column>
            <template #header>
              <el-button type="primary" @click="addList(2)">新增</el-button>
            </template>
            <template #default="{ row, $index }">
              <el-button link type="primary" v-if="row.isEdit" @click="saveTable(2, row)">保存 </el-button>
              <el-button link type="primary" v-else @click="editTable(2, row)">编辑</el-button>
              <el-button link type="danger" @click="deleteTable(2, $index)">删除</el-button>
              <el-button link type="primary" v-if="row.isEdit" @click="addAddress($index,row)">添加考勤地址</el-button>
            </template>
          </el-table-column>
        </el-table>
        <p>根据WiFi考勤(精确定位到办公室内，可添加多个办公室WiFi)</p>
        <el-table :data="tableData[0].attendanceWifiType">
          <el-table-column v-for="(obj, index) in tableThreeHeader.slice(0, tableThreeHeader.length - 1)" :key="index" :label="obj.label" :prop="obj.prop">
            <template #default="{ row }">
              <el-input v-model="row[obj.prop]" placeholder="请输入" v-if="row.isEdit" />
              <span v-else>{{ row[obj.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="适用人员">
            <template #default="{ row }">
              <el-select
                v-model="row.attendanceUsersId"
                multiple
                collapse-tags
                collapse-tags-tooltip
                placeholder="请选择"
                @blur="showNickname(row.attendanceUsersId, row)"
                v-if="row.isEdit"
              >
                <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName" :value="item.userId" />
              </el-select>
              <div v-else>
                <span v-for="item in row.attendanceUsersName">{{ item }}&nbsp; </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column>
            <template #header>
              <el-button type="primary" @click="addList(3)">新增</el-button>
            </template>
            <template #default="{ row, $index }">
              <el-button v-if="row.isEdit" link type="primary" @click="saveTable(3, row)">保存 </el-button>
              <el-button v-else link type="primary" @click="editTable(3, row)">编辑</el-button>
              <el-button link type="danger" @click="deleteTable(3, $index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <el-dialog v-model="addressDialog" title="添加考勤地址" @open="showMap">
      <div id="mars3dcontent"></div>
      <el-form :model="dialogForm">
        <el-form-item label="经度">
          <el-input v-model="dialogForm.x" />
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="dialogForm.y" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input disabled v-model="dialogForm.address" />
        </el-form-item>
        <div style="display: flex; justify-content: space-between">
          <div>
            <el-button type="primary" @click="bindMourseClick">图上拾取</el-button>
            <el-button type="primary" @click="getAddressFormtdt">地址转化</el-button>
          </div>
          <el-button type="primary" @click="closeDialog">确定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, toRaw} from "vue";
import { useRouter, useRoute } from "vue-router";
import { getUserList, addAttendanceSetting, getByIdAttendanceSetting,updateAttendanceSetting} from "@/api/personnelManagement";
import { mapOptions } from "@/utils/mapOptions";
import { tiandiMapKey, tiandituAPI } from "@/utils/config";
import { ElMessage } from "element-plus";
import "mars3d-cesium/Build/Cesium/Widgets/widgets.css"; //依赖的cesium库本身css
import "mars3d/dist/mars3d.css";
import * as mars3d from "mars3d";
const eventTarget = new mars3d.BaseClass();
const router = useRouter();
const route = useRoute();
const isEditOne = ref(true);
const userOptions = ref([]) as any;
const addressDialog = ref(false);
const diffInMs = ref("");
const indexNum = ref(0);
const dialogForm = reactive({
  address: "",
  x: 0,
  y: 0,
});
const tableData = ref([
  {
    attendanceAddressType: [
      {
        // address: "",
        attendanceAddress: "",
        attendanceUsers: [],
        attendanceUsersId: [],
        attendanceUsersName: [],
        effectiveRange: 0,
        x: 0,
        y: 0,
        isEdit: true,
      },
    ],
    attendanceWifiType: [
      {
        address: "",
        attendanceUsers: [],
        attendanceUsersId: [],
        attendanceUsersName: [],
        macAddress: "",
        wifiName: "",
        isEdit: true,
      },
    ],
    effectiveTime: "",
    name: "",
    startTime: [],
    endTime: [],
    type: 0,
    way: 0,
    workTime: "",
  },
]);
const tableOneHeader = [
  {
    label: "上班打卡时间",
    prop: "startTime",
  },
  {
    label: "下班打卡时间",
    prop: "endTime",
  },
  {
    label: "生效时间",
    prop: "effectiveTime",
  },
];

const tableThreeHeader = [
  {
    label: "WiFi名称",
    prop: "wifiName",
  },
  {
    label: "MAC地址",
    prop: "macAddress",
  },
  {
    label: "地址",
    prop: "address",
  },
  {
    label: "使用人员",
    prop: "attendanceUsers",
  },
];
const getDetail = async () => {
  // console.log(route.query.id, "1111");
  if (route.query.id != undefined) {
    const { data, code } = await getByIdAttendanceSetting(route.query.id);
    if (code == 200) {
      tableData.value[0]=data
      tableData.value[0].startTime =data.startTime.split("~")
      tableData.value[0].endTime =data.endTime.split("~")
      diffInMs.value=data.workTime
      // console.log("更新成功",data);
    }
  }
};
getDetail();
const goBack = () => {
  router.go(-1);
};
const getUserLists = async () => {
  const { data, code } = await getUserList();
  if (code == 200) {
    userOptions.value = data;
  }
};
getUserLists();
/**保存 */
const saveTable = (num, row?: any) => {
  if (num == 1) {
    isEditOne.value = !isEditOne.value;
    calculateTimeDifference(tableData.value[0].startTime, tableData.value[0].endTime);
  } else {
    row.isEdit = !row.isEdit;
  }
};
/**编辑 */
const editTable = (num, row?: any) => {
  if (num == 1) {
    isEditOne.value = !isEditOne.value;
    // console.log(row.startTime);

    tableData.value[0].startTime = row.startTime.split("~");
    tableData.value[0].endTime = row.endTime.split("~");
  } else {
    row.isEdit = !row.isEdit;
  }
};
/**删除 */
const deleteTable = (num, index) => {
  if (num == 3) {
    tableData.value[0].attendanceWifiType.splice(index, 1);
  }
  if (num == 2) {
    tableData.value[0].attendanceAddressType.splice(index, 1);
  }
};
/**新增 */
const addList = (num) => {
  if (num == 3) {
    tableData.value[0].attendanceWifiType.push({
      address: "",
      attendanceUsers: [],
      attendanceUsersId: [],
      attendanceUsersName: [],
      macAddress: "",
      wifiName: "",
      isEdit: true,
    });
  } else {
    tableData.value[0].attendanceAddressType.push({
      attendanceAddress: "",
      attendanceUsers: [],
      attendanceUsersId: [],
      attendanceUsersName: [],
      effectiveRange: 0,
      x: 0,
      y: 0,
      isEdit: true,
    });
  }
};
/**地图弹框 */
let map;
const addAddress = (index: number,row) => {
  addressDialog.value = true;
  indexNum.value = index;
  dialogForm.x=row.x
  dialogForm.y=row.y
  dialogForm.address=row.attendanceAddress
};
const showMap = () => {
  map = new mars3d.Map("mars3dcontent", mapOptions);
};
eventTarget.on("clickMap", (event: any) => {
  dialogForm.x = marsUtilFormtNum(event.point.lng, 6);
  dialogForm.y = marsUtilFormtNum(event.point.lat, 6);
  tableData.value[0].attendanceAddressType[indexNum.value].x = marsUtilFormtNum(event.point.lng, 6);
  tableData.value[0].attendanceAddressType[indexNum.value].y = marsUtilFormtNum(event.point.lat, 6);
  // 更新面板
  updateMarker(false, event.point.lng, event.point.lat, event.point.alt);
});
const bindMourseClick = () => {
  map.setCursor(true);
  map.once(mars3d.EventType.click, (event) => {
    map.setCursor(false);
    const cartesian3 = event.cartesian;
    const point = mars3d.LngLatPoint.fromCartesian(cartesian3);
    point.format(); // 经度、纬度、高度
    eventTarget.fire("clickMap", { point });
  });
};
// 添加坐标图标
let pointEntity;
const updateMarker = (hasCenter, jd, wd, alt) => {
  const position = [jd, wd, alt];

  if (pointEntity == null) {
    pointEntity = new mars3d.graphic.PointEntity({
      position,
      style: {
        color: "#3388ff",
        pixelSize: 10,
        outlineColor: "#ffffff",
        outlineWidth: 2,
      },
    });
    map.graphicLayer.addGraphic(pointEntity);
  } else {
    pointEntity.position = position;
  }

  if (hasCenter) {
    pointEntity.flyTo({ radius: 1000 });
  }
};
// 坐标转化
const marsUtilFormtNum = (item, num) => {
  return mars3d.Util.formatNum(item, num);
};
// 逆地理转换
const getAddressFormtdt = () => {
  if (dialogForm.x && dialogForm.y) {
    const postStr = JSON.stringify({ lon: dialogForm.x, lat: dialogForm.y, ver: 1 });
    const url = `${tiandituAPI}?postStr=${postStr}&type=geocode&tk=${tiandiMapKey}`;
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        if (data.status === "0") {
          dialogForm.address = data.result.formatted_address;
          tableData.value[0].attendanceAddressType[indexNum.value].attendanceAddress = data.result.formatted_address;
        } else {
          ElMessage.error("获取地址失败");
        }
      })
      .catch((error) => ElMessage.error(error));
  }
};
//关闭弹框
const closeDialog = () => {
  addressDialog.value = false;
  map.destroy();
  map = null;
  dialogForm.x = 0;
  dialogForm.y = 0;
  dialogForm.address = "";
  tableData;
};
// 表单提交
const saveForm = async () => {
  const submitForm = reactive({}) as any;
  Object.keys(tableData.value[0]).map((key) => {
    submitForm[key] = tableData.value[0][key];
  });
  const code=ref(0)
  // console.log(typeof submitForm.startTime=='object',submitForm.startTime.length==2);
  
  if(submitForm.startTime.length==2&&typeof submitForm.startTime=='object'){
    submitForm.startTime=submitForm.startTime.join("~")
    submitForm.endTime=submitForm.endTime.join("~")
  }
  if(route.query.id!=undefined){
    //编辑提交
    const data=await updateAttendanceSetting(submitForm)
    code.value=data.code
  }else{
    // 新增提交
    const data = await addAttendanceSetting(submitForm);
    code.value=data.code
  }
  if (code.value == 200) {
    ElMessage.success("保存成功");
  }
  console.log(tableData.value[0], submitForm, "提交表单");
};
// 显示昵称
const showNickname = (arr1, arr2) => {
  arr2.attendanceUsers = userOptions.value.filter((item) => arr1.includes(item.userId)).map((items) => toRaw(items));
  arr2.attendanceUsersName = userOptions.value.filter((item) => arr1.includes(item.userId)).map((item) => item.nickName);
};
/**计算时间差 */
const calculateTimeDifference = (time1, time2) => {
  if (time1 != null && time2 != null) {
    const time1Arr1 = time1[0].split(":");
    const time1Arr2 = time1[1].split(":");
    const time2Arr1 = time2[0].split(":");
    const time2Arr2 = time2[1].split(":");

    const time1Seconds1 = time1Arr1[0] * 3600 + time1Arr1[1] * 60 + time1Arr1[2] * 1;
    const time1Seconds2 = time1Arr2[0] * 3600 + time1Arr2[1] * 60 + time1Arr2[2] * 1;
    const time2Seconds1 = time2Arr1[0] * 3600 + time2Arr1[1] * 60 + time2Arr1[2] * 1;
    const time2Seconds2 = time2Arr2[0] * 3600 + time2Arr2[1] * 60 + time2Arr2[2] * 1;
    const diffInSeconds1 = Math.abs(time1Seconds2 - time1Seconds1);
    const diffInSeconds2 = Math.abs(time2Seconds2 - time2Seconds1);
    const diffInSeconds = diffInSeconds1 + diffInSeconds2;
    diffInMs.value = `${Math.floor(diffInSeconds / 3600)}小时${Math.floor((diffInSeconds % 3600) / 60)}分钟${diffInSeconds % 60}秒`;
    tableData.value[0].workTime = diffInMs.value;
    tableData.value[0].startTime = time1.join("~");
    tableData.value[0].endTime = time2.join("~");
  }
};

</script>

<style scoped lang="scss">
.addTitle {
  color: #606266;
  font-weight: 700;
  font-size: 22px;
}
</style>
